package cn.tedu._03vehicle.base.exception;

import cn.tedu._03vehicle.base.response.JsonResult;
import cn.tedu._03vehicle.base.response.StatusCode;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {


    @ExceptionHandler(IllegalArgumentException.class)
    public JsonResult doHandleIllegalArgumentException(IllegalArgumentException ex) {

        String data = ex.getMessage();
        log.error("参数异常信息："+data);
        return JsonResult.fail(data);
    }


    @ExceptionHandler(ConstraintViolationException.class)
    public JsonResult doHandleConstrantViolationException(ConstraintViolationException  ex) {

        String data = ex.getMessage();
        Pattern pattern = Pattern.compile(": (.*)");
        Matcher matcher = pattern.matcher(data);

        if (matcher.find()) {
            // 提取第一个捕获组的内容（即 (.*) 匹配的部分）
            data = matcher.group(1);
        } else {
            // 处理未找到匹配的情况
            System.out.println("未找到匹配的内容: " + data);
        }
        log.error("参数校验异常信息："+data);
        return new JsonResult(StatusCode.VALIDATED_ERROR,data);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JsonResult doHandleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {

        String data = ex.getBindingResult().getFieldError().getDefaultMessage();
        log.error("参数校验异常信息："+data);
        return new JsonResult(StatusCode.VALIDATED_ERROR,data);
    }

    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public JsonResult doHandleMaxUploadSizeExceededException(MaxUploadSizeExceededException ex) {

        String data = "上传文件大小超出限制,单个文件上传大小不超过100MB,单次多个文件上传不超过500MB";
        log.error("doHandleMaxUploadSizeExceededException："+data);
        return new JsonResult(StatusCode.MAX_UPLOAD_SIZE_ERROR,data);
    }

    @ExceptionHandler(RuntimeException.class)
    public JsonResult doHandleRuntimeException(RuntimeException ex) {

        String data = ex.getMessage();
        log.error("运行时异常信息："+data);
        return JsonResult.fail(data);
    }

//    @ExceptionHandler(Throwable.class)
//    public JsonResult doHandleThrowable(Throwable ex) {
//
//        String data = ex.getMessage();
//        log.error("未知异常信息："+data);
//        return new JsonResult(StatusCode.FAIL_ERROR,data);
//    }











}
